package lock.spinlock;

import sun.awt.windows.ThemeReader;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Brook
 */
public class SpinLock {

    private AtomicReference<Thread> sign = new AtomicReference<>();

    public void lock() {
        Thread current = Thread.currentThread();
        while (!sign.compareAndSet(null, current)) {
            System.out.println("自旋获取失败");
        }
    }

    public void unlock() {
        Thread current = Thread.currentThread();
        sign.compareAndSet(current, null);
    }

    public static void main(String[] args) {
        SpinLock spinLock = new SpinLock();
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"开始尝试获取自旋锁");
                spinLock.lock();
                System.out.println(Thread.currentThread().getName()+"获取到了自旋锁");

                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println(Thread.currentThread().getName()+"释放");
                }finally {
                    spinLock.unlock();
                }
            }
        };

        Thread te1 = new Thread(runnable);
        Thread te2 = new Thread(runnable);
        te1.start();
        te2.start();
    }
}